/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.multicontext.resolver;

import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.multicontext.classloader.PlatformClassloader;
import io.iec.edp.caf.multicontext.context.PlatformApplicationContext;
import io.iec.edp.caf.multicontext.support.ModuleManager;
import io.iec.edp.caf.rpc.api.annotation.GspServiceBundle;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.context.ApplicationContext;

import java.lang.annotation.Annotation;
import java.net.URLClassLoader;
import java.util.HashSet;
import java.util.Set;

/***
 * AppManager的协调器
 *
 */
@Slf4j
public class AppManagerResolver implements io.iec.edp.caf.commons.spi.AppManagerResolver {
    @Override
    public Set<Class<?>> getClassesWithAnnotation(Class<? extends Annotation> annotation) {
        Set<Class<?>> result=new HashSet<>();
        //获取模块内的Rpc服务列表
        ApplicationContext ctx = SpringBeanUtils.getApplicationContext();
        if (ctx instanceof PlatformApplicationContext) {
            ModuleManager moduleManager = ((PlatformApplicationContext) ctx).getModuleManager();
            result.addAll(moduleManager.getClassesWithAnnotation(GspServiceBundle.class));
        }

        return result;
    }

    @Override
    public URLClassLoader getSuClasspath(String msu) {
        var classloader = getPlatformClassloader();
        if(log.isDebugEnabled()){
            log.debug("current classloader type [{}]", classloader.getClass().getName());
        }
        return ((PlatformClassloader) classloader).getSuClasspath(msu);
    }

    private static ClassLoader getPlatformClassloader() {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        //迭代寻找需要的classloader
        while (cl != null) {
            //如果识别为并行启动
            if (cl instanceof PlatformClassloader) {
                return cl;
            }
            cl = cl.getParent();
        }
        return Thread.currentThread().getContextClassLoader();
    }
}
